package com.huike.utils;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.sql.rowset.serial.SerialBlob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Blob;
import java.sql.SQLException;

/**
 * 文件工具类
 */
public class FileUtils {

    // MultiPartFile类型文件转成Blob
    public static Blob MultiPartFileToBlob(MultipartFile file) {
        Blob blob = null;
        try {
            blob = new SerialBlob(file.getBytes());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            System.out.println("file to blob error.");
            e.printStackTrace();
        }

        return blob;
    }

    //字节流转文件
    public static String writeFile(HttpServletRequest req, byte[] file, String originalFilename) throws IOException {
        // 获取文件上传要保存到的文件地址
        String path = req.getSession().getServletContext().getRealPath("/upload");
        // 如果文件夹不存在则创建该文件夹
        File uploadDir = new File(path);
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }

        FileOutputStream out = new FileOutputStream(path+'/'+originalFilename);
        out.write(file);
        out.flush();
        out.close();

        // 文件上传后的访问路径
        //http://localhost:8080/SMS
        String basePath = req.getRequestURL().substring(0,req.getRequestURL().lastIndexOf("/"));
        System.out.println(basePath);
        return basePath + "/upload/" + originalFilename;
    }

}
